import React, { Component } from 'react'
import {
    View,
    StyleSheet,
    Image,
    ScrollView,
    TouchableOpacity,
    Text,
    Dimensions,
    Modal
} from 'react-native'

import ImageCropPicker from 'react-native-image-crop-picker';
import RNFS from 'react-native-fs';
import ImageViewer from 'react-native-image-zoom-viewer';
import NavBar from '../../../components/PublicHeader';
import fetchWebApi from '../../../public/WebApi/fetchBase';
import getStorageValue from '../../../utils/getStorageValue';
import Layer from '../../../utils/Layer';

import {
    Constant
} from '../../../public/js/constant';
import {
    GET_SELFPRESENTATION,
    DELETE_ALBUMINFDOATA
} from '../../../public/WebApi/myInfoDataInterface/userInfoListApi';

// 获取当前手机屏幕的 宽 / 高
const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;

export default class myAlbum extends Component {
    constructor(props) {
        super(props)
        this.state = {
            topTitle: "我的相册",
            deleteMark: require('../../../assets/images/socialcircle/delete_mark.png'),
            groupImg: require("../../../assets/images/iconResources/Group17.png"),
            headerRightImage: require("../../../assets/images/headerIcon/AddFriends.png"),
            myAlbumDeleteMark: false, // 相册删除按钮默认值
            myAlbumDeleteNum: null, // 判断相册数据是否被清空
            myAlbumDatas: [], // 照片列表
            content: "",// base64 本地相册地址转换
            isImageShow: false,
            imageIndex: 0,
            remarks: [],
            i: 0
        };
    }

    componentDidMount = () => {
        // 初次渲染时 获取用户信息列表
        this.getUserSelfPresentation()
    }

    _renderImage(item, index) {
        const {
            remarks,
            deleteMark,
            myAlbumDeleteMark,
        } = this.state
        remarks[this.state.i++] = item.title
        return (
            <View style={styles.myAlbumDatasWarper}
                key={index}>
                {/* 详情跳转 */}
                <TouchableOpacity onPress={
                    this._openMax.bind(this, index)}
                    key={'image' + index}>
                    <View style={styles.items}>
                        <Image style={styles.systemPrompt}
                            source={{ uri: item.url }} />
                    </View>
                </TouchableOpacity>
                {/* 相册删除按钮区 */}
                <View style={styles.myAlbumDatasMarkBox}>
                    <TouchableOpacity onPress={() => {
                        this.myAlbumDeleteMark(item.id)
                    }}>
                        {myAlbumDeleteMark ?
                            <Image style={styles.myAlbumDeleteMark}
                                source={deleteMark} />
                            : null}
                    </TouchableOpacity>
                </View>
            </View>
        );
    }

    _openMax(index) {
        this.setState({
            isImageShow: true,
            imageIndex: index,
            myAlbumDeleteMark: false
        });
    }

    // 获取用户自我展示列表
    async getUserSelfPresentation() {
        const {
            myAlbumDeleteNum
        } = this.state
        const res = await fetchWebApi(GET_SELFPRESENTATION,
            {
                token: await getStorageValue(Constant.TOKEN)
            }, 'GET');
        if (res.status === 200) {
            this.setState({
                myAlbumDatas: res.data
            })

            if (res.data.length > 0 &&
                myAlbumDeleteNum == 1) {
                this.setState({
                    myAlbumDeleteMark: true
                })
            } else {
                this.setState({
                    myAlbumDeleteMark: false
                })
            }
        } else {
            // 弹窗提示
            Layer.showMsg("获取自我展示失败");
            return
        }
    }

    // 照片删除方法
    async myAlbumDeleteMark(ID) {
        const res = await fetchWebApi(DELETE_ALBUMINFDOATA,
            {
                token: await getStorageValue(Constant.TOKEN),
                id: ID
            }, 'DELETE');
        if (res.status === 200) {
            // 弹窗提示
            Layer.showMsg("删除成功");
            // 删除后重新刷新数据
            this.getUserSelfPresentation()
        } else {
            Layer.showMsg("删除失败");
            return
        }
    }

    // 重新获取数据
    getUserSelfFn = () => {
        this.getUserSelfPresentation()
    }

    // 获取本地相册
    AlbumItemimages = () => {
        this.setState({
            myAlbumDeleteNum: null,
            myAlbumDeleteMark: false
        })
        ImageCropPicker.openPicker({
            width: 300,
            height: 400,
            hideBottomControls: true
        }).then(itemimages => {
            //  获取图片类型
            const typeArr = itemimages.path.split(".")
            // // 判断图片最多可选数量
            if (itemimages.length > 1) {
                Layer.showMsg("最多可上传一张");
                return
            }
            RNFS.readFile(itemimages.path, 'base64')
                .then(content => {
                    // base64 本地相册地址转换
                    this.setState({
                        content: content
                    })
                    // 跳转上传页面 把当前照片传到子级
                    this.props.navigation.navigate("upload", {
                        itemimages: itemimages.path,
                        content: this.state.content,
                        type: typeArr[2],
                        getUserSelfFn: () => {
                            // 重新获取相册数据
                            this.getUserSelfFn();
                        },
                    })
                })
                .catch(err => {
                    Layer.showMsg('图片读取失败');
                    return
                });
        })
    }

    render() {
        const {
            topTitle,
            myAlbumDeleteMark,
            myAlbumDatas,
            isImageShow,
            imageIndex,
            remarks,
            groupImg
        } = this.state
        return (
            <View style={styles.warper}>
                {/* 导航栏 */}
                <NavBar
                    navigation={this.props.navigation}
                    title={topTitle}
                    titleColor={"#333"}
                    right={"编辑"}
                    pressRight={() => {
                        this.setState({
                            myAlbumDeleteMark: !myAlbumDeleteMark,
                            myAlbumDeleteNum: 1
                        })
                    }
                    }
                />
                {/* 列表 */}
                <ScrollView>
                    <View style={styles.padlr}>
                        <View style={styles.row}>
                            {myAlbumDatas.map((item, index) => {
                                return this._renderImage(item, index);
                            })}
                            {isImageShow ?
                                <Modal visible={true} transparent={true}
                                    onRequestClose={() => {
                                        this.setState({
                                            isImageShow: false,
                                        });
                                    }}>

                                    <ImageViewer
                                        imageUrls={myAlbumDatas}
                                        style={{ color: 'black' }}
                                        onCancel={() => {
                                            this.setState({
                                                isImageShow: false,
                                            });
                                        }}
                                        index={imageIndex}
                                        saveToLocalByLongPress={false}
                                        backgroundColor="white"
                                        renderHeader={() => {
                                        }}
                                        renderFooter={(index) => {
                                            return (
                                                <>
                                                    {remarks[index] == '' ?
                                                        null :
                                                        <>
                                                            <View style={{
                                                                display: 'flex',
                                                                justifyContent: 'center',
                                                                padding: 20
                                                            }}>
                                                                <Text style={{
                                                                    color: 'white',
                                                                    fontSize: 20,
                                                                }}>
                                                                    {remarks[index]}
                                                                </Text>

                                                            </View>
                                                        </>}
                                                </>
                                            )
                                        }}
                                        footerContainerStyle={{
                                            width: '100%',
                                            backgroundColor: 'gray',
                                            opacity: 0.5
                                        }}
                                    >
                                    </ImageViewer>
                                </Modal>
                                : null}
                            {/* 判断图片已添加数量 */}
                            {myAlbumDatas.length < 9 ?
                                <TouchableOpacity onPress={() => {
                                    // 获取本地相册
                                    this.AlbumItemimages()
                                }}>
                                    {/* 添加按钮 */}
                                    <View style={styles.addSystemPrompt}>
                                        <Image style={styles.systemPromptAdd}
                                            source={groupImg} />
                                    </View>
                                </TouchableOpacity>
                                : null}
                        </View>
                    </View>
                </ScrollView>
            </View>
        )
    }
}
const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 32,
        backgroundColor: 'transparent'
    },
    warper: {
        flex: 1,
        backgroundColor: "#fff"
    },
    row: {
        flexDirection: "row",
        justifyContent: "flex-start",
        flexWrap: "wrap",
    },
    items: {
        marginTop: 7,
        marginBottom: 5,
        marginRight: width / 25,
        marginLeft: width / 25,
        borderRadius: 3,
    },
    myAlbumDatasWarper: {
        position: "relative"
    },
    systemPrompt: {
        width: width / 4,
        height: height / 8,
        borderRadius: 4
    },
    myAlbumDeleteMark: {
        width: 20,
        height: 20,
    },
    myAlbumDatasMarkBox: {
        position: "absolute",
        top: 1,
        right: 6
    },
    systemPromptAdd: {
        width: 40,
        height: 40,
    },
    addSystemPrompt: {
        justifyContent: "center",
        alignItems: "center",
        marginRight: width / 25,
        marginLeft: width / 25,
        width: width / 4,
        height: height / 8,
        marginTop: 7,
        borderRadius: 3,
        backgroundColor: "#E8E8E8"
    }
})